import { IDiff, IManifest } from "./interface";

/** 补全文件md5 */
function getFilePathWithMd5(subPath: string, encode: string) {
    return subPath.substr(0, subPath.lastIndexOf(".")) + `.${encode}` + subPath.substring(subPath.lastIndexOf("."), subPath.length);
}

/**
 * 比较俩个版本的Manifest的内容
 * @param {JSON} oldManifest 旧版本Manifest
 * @param {JSON} newManifest 新版本Manifest
 */
export default function (oldManifest: IManifest, newManifest: IManifest) {
    let oldAssets = oldManifest.assets;
    let newAssets = newManifest.assets;
    let diff: IDiff = {
        oldVersion: oldManifest.version,
        newVersion: newManifest.version,
        dels: [],
        adds: [],
        modifieds: [],
        diffFiles: [],
        fileCount: 0,
        cdnSize: 0,
    }
    for (let key in newAssets) {
        if (!oldAssets[key]) {
            diff.adds.push({
                path: key,
                size: newAssets[key].size,
                diffSize: newAssets[key].size
            });
            diff.diffFiles.push(key);
            diff.fileCount++;
            diff.cdnSize += newAssets[key].size;
        } else {
            if (oldAssets[key].md5 != newAssets[key].md5 || key.indexOf("manifest") != -1) {
                diff.modifieds.push({
                    path: key,
                    size: newAssets[key].size,
                    diffSize: newAssets[key].size - oldAssets[key].size
                })
                diff.diffFiles.push(key);
                diff.fileCount++;
                diff.cdnSize += newAssets[key].size;
            }
        }
    }

    for (let key in oldAssets) {
        if (!newAssets[key]) {
            diff.dels.push({
                path: key,
                size: oldAssets[key].size
            })
        }
    }
    diff.diffFiles.push(`version.${newManifest.version}.manifest`);
    diff.fileCount++;
    diff.diffFiles.push(`project.${newManifest.version}.manifest`);
    diff.fileCount++;
    return diff;
}
